<template>
	<view>
		<view class="store-box" @click="openStorePopup">
			<view class="gg-tips">{{ $t('navigation.store', 'Store') }}</view>
		</view>
		<!-- 商店弹窗 -->
		<uni-popup ref="storePopup" type="center">
			<view class="pup-box model-content">
				<image class="close-img" src="/static/img/close.png" mode="aspectFit" @click="closeStorePopup"></image>
				<view class="title">{{ $t('store.store', 'STORE') }}</view>
				<view class="contents">
					<view class="tab-box flex-l">
						<view class="tab-item" :class="{ active: storeType === 'seed' }"
							@click="handleStoreType('seed')">{{ $t('store.seed', 'Seed') }}</view>
						<view class="tab-item" :class="{ active: storeType === 'material' }"
							@click="handleStoreType('material')">{{ $t('store.material', 'Material') }}</view>
					</view>
					<view v-if="storeType === 'seed'" class="body-box">
						<view class="flex-top-l">
							<view class="shop-item" v-for="(item, index) in storeItems" :key="index"
								@click="handleOpenBuySeedPopup(item)">
								<view>
									<image class="shop-img" :src="projectConfig.imgPrefix + item.seed_image"
										mode="aspectFit" style="width: 36px;">
									</image>
									<view class="prive-items flex-center">
										<image class="gold-img" src="/static/img/gold.png" mode="aspectFit"></image>
										<text class="text">{{ Number(item.price).toFixed(2) }}</text>
									</view>
								</view>
								<view v-if="item.price > Number(userInfo.coin)" class="mask-box flex-center">
									<image class="ban-icon" src="/static/img/hidden.png" mode="aspectFit"></image>
								</view>
							</view>
						</view>
					</view>
					<view v-if="storeType === 'material'" class="body-box flex-top">
						<view class="shop-item shop-item-dj" v-for="(item, index) in storeItems" :key="index"
							@click="handleOpenBuyMaterialPopup(item)">
							<image class="shop-img" :src="projectConfig.imgPrefix + item.seed_image" mode="aspectFit">
							</image>
							<view class="prive-items flex-center">
								<image class="gold-img" src="/static/img/gold.png" mode="aspectFit"></image>
								<text class="text">{{ Number(item.price).toFixed(2) }}</text>
							</view>
						</view>
						<!-- <view class="shop-item shop-item-dj">
							<image class="shop-img" src="/static/img/stone.png" mode="aspectFit"></image>
							<view class="prive-items flex-center">
								<image class="gold-img" src="/static/img/gold.png" mode="aspectFit"></image>
								<text class="text">50.00</text>
							</view>
						</view>
						<view class="shop-item shop-item-dj">
							<image class="shop-img" src="/static/img/wood.png" mode="aspectFit"></image>
							<view class="prive-items flex-center">
								<image class="gold-img" src="/static/img/gold.png" mode="aspectFit"></image>
								<text class="text">10.00</text>
							</view>
						</view> -->
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 购买弹窗 -->
		<uni-popup ref="buyPopup" type="center">
			<view class="buyPopup-box model-content">
				<image src="/static/img/close.png" mode="aspectFit" class="close-img" @click="closeBuyPopup" />
				<view class="title text-overflow">{{ getItemDisplayName(currentItem) }}</view>
				<view class="contents">
					<image class="greens-deta" :src="projectConfig.imgPrefix + currentItem.seed_image" />
					<view class="flex-lr deta-list">
						<view>{{ $t('store.price', 'Price') }}：</view>
						<view class="flex-r">
							<image class="coin" src="/static/img/gold.png" />
							<view class="num">{{ currentItem.price }}</view>
						</view>
					</view>
					<view class="flex-lr deta-list">
						<view>{{ $t('store.current_inventory', 'Current inventory') }}：</view>
						<view class="num">{{ currentItem?.inventory || '0' }}</view>
					</view>
					<view class="flex-lr deta-list">{{ $t('store.material_description', 'Material description') }}：</view>
					<view class="deta-title">{{ getItemDisplayName(currentItem) }}</view>
					<view class="flex-lr sd-count-wrap">
						<view class="count-item flex-lr">
							<image class="js-icon" src="/static/img/jian.png" @click="decreaseCount" />
							<view>{{ buyCount }}</view>
							<image class="js-icon" src="/static/img/jia.png" @click="increaseCount" />
						</view>
						<view class="count-item flex-lr">
							<image class="js-icon" src="/static/img/gold.png" />
							<view>{{ totalPrice }}</view>
						</view>
					</view>
				</view>
				<view class="copy-btn" @click="handleBuy">{{ $t('store.buy', 'BUY') }}</view>
			</view>
		</uni-popup>

		<loader />
	</view>
</template>

<script>
import { systemApi } from '@/request/system.js'
import { userApi } from '@/request/user.js'
import { mapGetters } from 'vuex'
import projectConfig from '@/config/project.json'
import { mapState, mapActions } from 'vuex'
import { languageMixin } from '@/utils/language-mixin.js'

export default {
	name: 'StoreBox',
	mixins: [languageMixin],
	computed: {
		...mapGetters('user', ['usdtBalance', 'userInfo']),
		...mapState('user', ['friendHomeMode'])
	},
	data() {
		return {
			storeType: 'seed',
			storePopup: null,
			buyPopup: null,
			storeItems: [],
			projectConfig,
			currentItem: null,
			buyCount: 1,
			totalPrice: 0
		}
	},
	mounted() {
		// this.fetchSeeds()
	},
	methods: {
		...mapActions('user', ['getUserInfo']),
		// 关闭购买弹窗
		closeBuyPopup() {
			this.$refs.buyPopup.close();
			this.buyCount = 1;
			this.totalPrice = 0;
		},

		// 处理购买
		async handleBuy() {
			if (this.currentItem) {
				let res = null
				if (this.storeType === 'seed') {
					res = await systemApi.buySeed({ storeId: this.currentItem.store_id, itemId: this.currentItem.seed_id, num: this.buyCount })
				} else {
					res = await systemApi.buyMaterial({ storeId: this.currentItem.store_id, itemId: this.currentItem.seed_id, num: this.buyCount })
				}
				if (res && res.msg === '4001') {
					await this.getUserInfo()
					uni.showToast({
						title: this.$t('messages.purchase_success', 'Purchase successfully'),
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: this.$t('messages.purchase_failed', 'Purchase failed'),
						icon: 'none'
					})
				}
				console.log('Purchase item:', this.currentItem.name, 'Quantity:', this.buyCount, 'Total price:', this.totalPrice);
				// 这里可以添加购买逻辑
				this.closeBuyPopup();
			}
		},

		handleOpenBuyMaterialPopup(item) {
			this.currentItem = item;
			this.buyCount = 1;
			this.totalPrice = item.price.toFixed(2) || 0;
			this.$refs.buyPopup.open();
		},
		handleOpenBuySeedPopup(item) {
			this.currentItem = item
			this.totalPrice = item.price.toFixed(2) || 0;
			this.buyCount = 1;
			console.log('this.currentItem', this.currentItem)
			this.$refs.buyPopup.open()
		},
		handleStoreType(type) {
			this.storeType = type;
			if (type === 'seed') {
				this.fetchSeeds()
			} else {
				this.fetchMaterials()
			}
		},
		openStorePopup() {
			if (!this.friendHomeMode) {
				this.storeType = 'seed'
				this.fetchSeeds()
				this.$refs.storePopup.open();
			}
		},
		closeStorePopup() {
			this.$refs.storePopup.close();
		},
		async fetchSeeds() {
			try {
				uni.$emit('show-loading')
				this.storeItems = []
				const res = await systemApi.getStoreSeeds({ page: 1, limit: 1000 })
				if (res && res.code === 200 && Array.isArray(res.data)) {
					// 按照price降序排序
					this.storeItems = res.data.sort((a, b) => b.price - a.price)
				}
			} catch (e) {
				console.error('Failed to get seed store', e)
			} finally {
				uni.$emit('hide-loading')
			}
		},
		async fetchMaterials() {
			try {
				uni.$emit('show-loading')
				this.storeItems = []
				const res = await systemApi.getStoreMaterials({ type: 1, page: 1, limit: 100 })
				if (res && res.code === 200 && Array.isArray(res.data)) {
					this.storeItems = res.data
				}
			} catch (e) {
				console.error('Failed to get material store', e)
			} finally {
				uni.$emit('hide-loading')
			}
		},
		decreaseCount() {
			if (this.buyCount > 1) {
				this.buyCount--;
				this.totalPrice = (this.currentItem.price * this.buyCount).toFixed(2);
			}
		},
		increaseCount() {
			this.buyCount++;
			this.totalPrice = (this.currentItem.price * this.buyCount).toFixed(2);
		},
		
		// 获取物品显示名称（使用多语言）
		getItemDisplayName(item) {
			return this.translateItemName(item)
		}
	}
}
</script>

<style scoped lang="scss">
.store-box {
	position: absolute;
	top: 182px;
	right: 10px;
	z-index: 90;
	width: 121px;
	height: 151px;
	background: url(/static/img/store.png) no-repeat;
	background-size: 100% 100%;

	.gg-tips {
		width: 78px;
		height: 43px;
	}
}

.model-content {
	width: 256px;
	min-height: 201px;
	padding: 7px 15px;
	box-sizing: border-box;
	position: relative;
}

.buyPopup-box {
	position: relative;
	background: url(/static/img/bg5.png) no-repeat;
	background-size: 100%;
	width: 256px;
	height: 418px;

	.close-img {
		position: absolute !important;
		width: 37px;
		height: 37px;
		right: -7px;
		top: 12px;
	}

	.title {
		color: #fef9e2;
		font-weight: 700;
		font-size: 17px;
		text-align: center;
	}

	.contents {
		padding: 33px 0 2px;
		overflow: initial;
		height: 254px;

		.greens-deta {
			width: 66px;
			height: 68px;
			text-align: center;
			margin-top: -16px;
			margin-bottom: 5px;
		}

		.deta-list {
			width: 100%;
			margin-bottom: 6px;
			color: #885625;
			font-size: 15px;
			font-weight: 700;

			.coin {
				width: 14px;
				height: 14px;
				margin-right: 2px;
			}

			.num {
				color: #ff9d1f;
				font-size: 15px;
				font-weight: 700;
			}
		}

		.deta-title {
			color: #5c8a50;
			font-size: 13px;
			font-weight: 700;
			text-align: left;
			height: 41px;
		}

		.sd-count-wrap {
			width: 100%;
			margin-bottom: 11px;

			.count-item {
				width: 87px;
				height: 24px;
				background: #5c8a50;
				box-shadow: 0 1px 2px 0 #43573f;
				border-radius: 12px;
				color: #fff;
				font-size: 18px;
				font-weight: 700;

				.js-icon {
					width: 31px;
					min-width: 31px;
					height: 31px;
					margin-left: -6px;
					margin-top: 3px;
				}
			}
		}
	}

	.copy-btn {
		width: 135px;
		height: 39px;
		line-height: 34px;
		text-align: center;
		margin: 0 auto;
		margin-top: 5px;
		background: url(/static/img/btn-bg.png) no-repeat;
		background-size: 100%;
		color: #fff;
		font-size: 18px;
		font-weight: 700;
	}
}

.pup-box {
	position: relative;
	background: url(/static/img/bg8.png) no-repeat;
	width: 362px;
	height: 418px;
	background-size: 100%;

	.close-img {
		position: absolute;
		width: 37px;
		height: 37px;
		right: 10px;
		top: 5px;
		z-index: 2;
	}

	.title {
		color: #fef9e2;
		font-weight: 700;
		font-size: 17px;
		text-align: center;
	}

	.contents {
		height: auto;
		padding: 0 26px;
		padding-top: 57px;
		box-sizing: border-box;

		.tab-box {
			width: 100%;
			padding-left: 8px;
			box-sizing: border-box;
			display: flex;

			.tab-item {
				height: 22px;
				padding: 0 6px;
				box-sizing: border-box;
				border-top-left-radius: 6px;
				border-top-right-radius: 6px;
				background: #c9f0c0;
				color: #6ba55e;
				font-size: 16px;
				font-weight: 700;
				margin-right: 3px;

				&.active {
					color: #fff;
					background: #e89241;
				}
			}
		}

		.body-box {
			overflow-x: hidden;
			width: 100%;
			height: 266px;
			background: #c9f0c0;
			box-shadow: 0 0.5px 0.5px 0 #84bf79;
			border-radius: 6px;
			padding: 3px 0;
			box-sizing: border-box;
			flex-wrap: wrap;

			.flex-top-l {
				flex-wrap: wrap;
				width: 106%;
				display: flex;
			}

			.shop-item {
				width: 69px;
				height: 86px;
				background: url(/static/img/shop-bg.png) no-repeat;
				background-size: 100%;
				position: relative;
				text-align: center;
				padding-top: 12px;
				box-sizing: border-box;

				.shop-img {
					width: 37px;
					height: 41px;
					display: block;
					margin: 0 auto;
					text-align: center;
					margin-bottom: 5px;
				}

				.prive-items {
					width: 100%;
					padding: 0 10px;
					box-sizing: border-box;
					color: #fff;
					font-size: 14px;
					font-weight: 700;
					display: flex;
					align-items: center;
					justify-content: center;

					.gold-img {
						width: 11px;
						min-width: 11px;
						height: 12px;
						margin-right: 1px;
					}

					.text {
						font-size: 12px;
						transform: scale(0.8);
						text-shadow: 1px 1px #de8a53;
					}
				}

				.mask-box {
					position: absolute;
					top: 4px;
					left: 5px;
					bottom: 5px;
					right: 5px;
					background: rgba(0, 0, 0, 0.6);
					border-radius: 3px;
					display: flex;
					align-items: center;
					justify-content: center;

					.ban-icon {
						width: 22px;
						height: 22px;
					}
				}

				&.shop-item-dj {
					background: url(/static/img/shop-bigbg.png) no-repeat;
					background-size: 100%;
					width: 121px;
					height: 126px;
					margin: 0 5px;
					margin-bottom: 5px;

					.shop-img {
						width: 62px;
						height: 62px;
						margin-bottom: 21px;
					}
				}
			}
		}
	}
}

.flex-l {
	display: flex;
}

.flex-center {
	display: flex;
	align-items: center;
	justify-content: center;
}

.flex-top {
	display: flex;
	justify-content: space-between;
	flex-wrap: wrap;
}
</style>